<template>
  <view class="goods-form p-20">
    <view class="form-wrapper">
      <u-form ref="formRef" :model="form" :rules="rules" label-width="6em">
        <u-form-item label="商品名称" prop="name" required>
          <up-input
            v-model="form.name"
            placeholder="请输入商品名称"
            clearable
          ></up-input>
        </u-form-item>
        <u-form-item label="商品标签" prop="extra_attributes2">
          <up-input
            ref="tagInputRef"
            v-model="tagValue"
            :maxlength="10"
            placeholder="输入后按回车添加"
            clearable
            @confirm="handleAddExtraAttributes"
          ></up-input>
        </u-form-item>
        <template v-if="form.extra_attributes2">
          <up-tag
            v-for="(tag, index) in form.extra_attributes2.label"
            :key="index"
            :text="tag"
            closable
            @close="form.extra_attributes2.label.splice(index, 1)"
          ></up-tag>
        </template>
        <u-form-item label="商品单位" prop="uom_id" required>
          <up-input v-model="uomLabel" placeholder="请选择单位" readonly>
            <template #suffix>
              <up-button type="primary" @click="handleOpenUomSheet">
                选择
              </up-button>
            </template>
          </up-input>
        </u-form-item>
        <u-form-item label="商品分类" prop="category_id" required>
          <up-input v-model="categoryLabel" placeholder="请选择分类" readonly>
            <template #suffix>
              <up-button type="primary" @click="handleOpenCategorySheet">
                选择
              </up-button>
            </template>
          </up-input>
        </u-form-item>
        <u-form-item label="运费模板" prop="exps_temp_id">
          <up-input
            v-model="templateLabel"
            placeholder="请选择运费模版"
            readonly
          >
            <template #suffix>
              <up-button type="primary" @click="handleOpenCategoryTemplate">
                选择
              </up-button>
            </template>
          </up-input>
        </u-form-item>
        <u-form-item label="最小销售数量" prop="min_sale_quantity" required>
          <up-input
            v-model="form.min_sale_quantity"
            placeholder="请输入最小销售数量"
            clearable
          ></up-input>
        </u-form-item>
        <u-form-item label="库存不足时下单" prop="is_order_out_stock">
          <up-switch v-model="form.is_order_out_stock"></up-switch>
        </u-form-item>
        <u-form-item label="是否热销" prop="is_hot">
          <up-switch v-model="form.is_hot"></up-switch>
        </u-form-item>
        <u-form-item label="收银必备" prop="is_pos">
          <up-switch v-model="form.is_pos"></up-switch>
        </u-form-item>
        <u-form-item label="新品推荐" prop="is_new_recommend">
          <up-switch v-model="form.is_new_recommend"></up-switch>
        </u-form-item>
        <u-form-item label="每周推荐" prop="is_week_recommend">
          <up-switch v-model="form.is_week_recommend"></up-switch>
        </u-form-item>
        <u-form-item label="封面图片" prop="image_url" required>
          <u-upload
            :maxCount="1"
            :fileList="files2"
            @afterRead="afterRead2"
            @beforeRead="beforeRead2"
            @delete="deletePic2"
            name="file"
            :multiple="true"
            :previewFullImage="true"
          ></u-upload>
        </u-form-item>
        <u-form-item label="商品多图" prop="sub_images" required>
          <u-upload
            :maxCount="9"
            :fileList="files"
            @afterRead="afterRead"
            @beforeRead="beforeRead"
            @delete="deletePic"
            name="file"
            :multiple="true"
            :previewFullImage="true"
          ></u-upload>
        </u-form-item>
        <u-form-item label="商品规格" prop="skus">
          <u-cell-group>
            <view class="flex items-center" v-for="(sku, index) in form.skus">
              <view class="flex-1">
                <u-cell
                  :key="index"
                  :title="formatSkuTitle(sku)"
                  :value="sku.sale_price"
                  :isLink="true"
                  :arrowDirection="sku.is_default ? 'right' : 'none'"
                  @click="handleSkuClick(sku, 'edit')"
                >
                </u-cell>
              </view>
              <view>
                <u-button
                  type="error"
                  size="mini"
                  @click="handleDeleteSku(sku, index)"
                >
                  删除
                </u-button>
              </view>
            </view>
          </u-cell-group>
        </u-form-item>
        <u-button
          type="primary"
          size="small"
          @click="handleSkuClick(undefined, 'add')"
          >新建规格</u-button
        >
        <u-form-item label="商品详情" prop="description">
          <up-parse :content="form.description"></up-parse>
        </u-form-item>
      </u-form>
      <u-button type="primary" @click="handleSubmit">提交</u-button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref } from "vue";
import {
  addGoods,
  goodsDetail,
  editGoods,
  getUomList,
  categories,
  getExpressTemplateList,
  delVariants,
} from "@/common/apis/goods.js";
import { uploadFile } from "@/common/apis/common.js";
import { onShow } from "@dcloudio/uni-app";

const props = defineProps({
  id: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "add",
  },
});

const tagInputRef = ref();
const tagValue = ref("");

const uomList = ref([]);
const uomLabel = ref("");

const categoryList = ref([]);
const categoryLabel = ref("");

const templateList = ref([]);
const templateLabel = ref("");

const formRef = ref();

const form = reactive({
  name: "",
  extra_attributes2: {
    label: [],
  },
  uom_id: "",
  category_id: "",
  exps_temp_id: undefined,
  min_sale_quantity: "",
  is_order_out_stock: false,
  is_hot: false,
  is_pos: false,
  is_new_recommend: false,
  is_week_recommend: false,
  image_url: "",
  sub_images: [],
});

const files = ref([]);

const files2 = ref([]);

const rules = {
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  uom_id: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择商品单位"));
        }
        callback();
      },
    },
  ],
  category_id: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择商品分类"));
        }
        callback();
      },
    },
  ],
  image_url: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请上传商品图片"));
        }
        callback();
      },
    },
  ],
  sub_images: [
    {
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error("请上传商品图片"));
        }
        callback();
      },
    },
  ],
};

async function fetchGoodsDetail(id) {
  const res = await goodsDetail(id);
  if (res) {
    form.id = res.id;
    form.name = res.name;
    form.description = res.description;
    form.skus = res.skus;
    if (!res.extra_attributes2) {
      res.extra_attributes2 = { label: [] };
    }
    form.extra_attributes2 = res.extra_attributes2;
    form.uom_id = res.uom.id;
    uomLabel.value = res.uom.name;
    form.category_id = res.category.id;
    categoryLabel.value = res.category.name;
    if (res.exps_temp) {
      form.exps_temp_id = res.exps_temp.id;
      templateLabel.value = res.exps_temp.name;
    }
    form.min_sale_quantity = res.min_sale_quantity;
    form.is_order_out_stock = res.is_order_out_stock;
    form.is_hot = res.is_hot;
    form.is_pos = res.is_pos;
    form.is_new_recommend = res.is_new_recommend;
    form.is_week_recommend = res.is_week_recommend;
    form.image_url = res.image_url;
    form.sub_images = res.sub_images;
    files.value = res.sub_images.map((item) => {
      return {
        url: item,
        status: "success",
        message: "",
      };
    });
    form.image_url = res.image_url;
    files2.value = [
      {
        url: res.image_url,
        status: "success",
        message: "",
      },
    ];
  }
}

function handleAddExtraAttributes() {
  if (tagValue.value.trim().length) {
    if (form.extra_attributes2.label.includes(tagValue.value)) {
      uni.$u.toast("标签已存在");
    } else {
      form.extra_attributes2.label.push(tagValue.value);
      tagValue.value = "";
    }
  } else {
    uni.$u.toast("请输入内容");
  }
}

async function fetchUomList() {
  const res = await getUomList();
  if (res) {
    uomList.value = res;
  }
}

async function fetchCategoryList() {
  const res = await categories();
  if (res) {
    categoryList.value = res;
  }
}

async function fetchExpressTemplateList() {
  const res = await getExpressTemplateList();
  if (res) {
    templateList.value = res.records;
  }
}

async function handleOpenUomSheet() {
  uni.showActionSheet({
    itemList: uomList.value.map((i) => i.name),
    success: (res) => {
      form.uom = uomList.value[res.tapIndex].id;
      uomLabel.value = uomList.value[res.tapIndex].name;
    },
  });
}

async function handleOpenCategorySheet() {
  uni.showActionSheet({
    itemList: categoryList.value.map((i) => i.name),
    success: (res) => {
      form.category_id = categoryList.value[res.tapIndex].id;
      categoryLabel.value = categoryList.value[res.tapIndex].name;
    },
  });
}

async function handleOpenCategoryTemplate() {
  uni.showActionSheet({
    itemList: templateList.value.map((i) => i.name),
    success: (res) => {
      form.exps_temp_id = templateList.value[res.tapIndex].id;
      templateLabel.value = templateList.value[res.tapIndex].name;
    },
  });
}

// 删除图片
function deletePic(event) {
  files.value.splice(event.index, 1);
  form.sub_images.splice(event.index, 1);
}
function beforeRead(event) {
  console.log(event);
}
// 新增图片
async function afterRead(event) {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = files.value.length;
  lists.map((item) => {
    files.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFile(lists[i].url);
    let item = files.value[fileListLen];
    files.value.splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: "success",
        message: "",
        url: result.url,
      })
    );
    form.sub_images.push(result.url);
    fileListLen++;
  }
}

// 删除图片
function deletePic2(event) {
  files2.value.splice(event.index, 1);
  form.image_url = "";
}
function beforeRead2(event) {
  console.log(event);
}
// 新增图片
async function afterRead2(event) {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = files2.value.length;
  lists.map((item) => {
    files2.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFile(lists[i].url);
    let item = files2.value[fileListLen];
    files2.value.splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: "success",
        message: "",
        url: result.url,
      })
    );
    form.image_url = result.url;
    fileListLen++;
  }
}

function formatSkuTitle(sku) {
  let title = "";
  if (sku.attributes) {
    title = sku.attributes.map((attr) => `${attr.key}:${attr.value}`).join(";");
  }
  return title;
}

function handleSkuClick(sku, type) {
  if (sku) {
    uni.navigateTo({
      url: `/pages/supplier/sku-form?product_id=${props.id}&variant_id=${sku.id}&type=${type}`,
    });
  } else {
    uni.navigateTo({
      url: `/pages/supplier/sku-form?product_id=${props.id}&type=${type}`,
    });
  }
}

function handleDeleteSku(sku) {
  uni.showModal({
    title: "提示",
    content: "是否删除该规格？",
    success: async (res) => {
      if (res.confirm) {
        const res = await delVariants(props.id, sku.id);
        uni.$u.toast("删除成功");
        form.skus = form.skus.filter((item) => item.id !== sku.id);
      }
    },
  });
}

async function handleSubmit() {
  const valid = await formRef.value.validate();
  formRef.value.validate().then(async () => {
    if (props.type == "add") {
      const res = await addGoods(form);
      uni.$u.toast("添加成功");
    } else {
      const res = await editGoods(form);
      uni.$u.toast("编辑成功");
    }
    uni.navigateBack();
  });
}

onShow(async () => {
  await fetchUomList();
  await fetchCategoryList();
  await fetchExpressTemplateList();
  if (props.id && props.type == "edit") {
    await fetchGoodsDetail(props.id);
  }
});
</script>

<style lang="scss" scoped>
.form-wrapper {
  padding: 20rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}
</style>
